<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/1/22
 * Time: 14:23
 */

namespace app\common\cachemodel\zlcr3;

use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zlcr3ConsultAuthCode extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr3_consult_auth_code';
    protected $cacheModel = 'astr_admin.auth_code';

    /**
     * 获取当前占星师授权状态
     * @param $astrId
     * @return bool
     * @throws \Exception
     */
    public function getAstrCodeStatus($astrId)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->setCacheKeyDetail('astr_code', $astrId)
            ->getDataAndSet(function () use ($astrId)
            {
                try
                {
                    $data = $this->where('astr_id', $astrId)->column('code', 'id');
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = [];
                }
                return $data;
            }, [], 'astr_code');
        return (bool)$data;
    }

    /**
     * 更新授权码使用
     * @param $astrId
     * @param $code
     * @param $data
     * @return bool
     */
    public function updateData($astrId, $code, $data)
    {
        try
        {
            $this->where('code', $code)->update($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $code)->setCache($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->setCacheKeyDetail('astr_code', $astrId)->rmCache('astr_code');
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
        return true;
    }

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            return $this->where(['code' => ['in', $ids]])->column('status,astr_id,expire_time', 'code');
        }
        catch (\Exception $e)
        {
            Log::write('Zlcr3ConsultAuthCode model => ()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['status', 'astr_id', 'expire_time']);
        }
        return $data;
    }
}
